<?php

abstract class Entidad extends Eloquent {
    
    public $tagModel; // Ej: TagRel
    public $imageModel; // Imagerel
    public $tagsId; // 'tag_rels.id'

    protected $guarded;
    protected $fillable;
    public $timestamps;
    
    function __construct(array $attributes = array()) {
        $this->timestamps = false;
    }


    /*----------- RELATIONS -----------*/
    
    public function tags() {
        return $this->belongsToMany($this->tagModel);
    }

    public function images(){
        return $this->belongsToMany($this->imageModel)->withPivot('position');
    }
    
    public function imagesOrdered(){
        return $this->images()->orderBy('position');
    }
    
    public function firstImage() {
        return $this->belongsToMany($this->imageModel)->withPivot('position')->orderBy('position')->take(1);
    }

    public function firstTag() {
        return $this->belongsToMany($this->tagModel)->orderBy('nombre')->take(1);
    }
    /*----------- FIN RELATIONS -----------*/
    
    public function getFirstTag() {
        // ojo: es tags, no es tags()
        return $this->tags->first();
    }

    
    public function getFirstTagName() {
        // ojo: es tags, no es tags()
        return $this->tags->first()->nombre;
    }

    public function getFirstImage() {
        // ojo: es imagesOrdered, no es imagesOrdered()
        return $this->imagesOrdered->first();
    }
    
//    public function validate($input) {
//        return Validator::make($input, self::rules);
//    }


    
    // que este ACTIVO estado = 1
    public function scopeActive($query) {
        return $query->where('estado', 1);
    }
    
    // que no pertenezcan a la tag_rels #1 ANONIMA
    public function scopeSinAnonimos($query) {
        return $query->whereHas('tags', function($query) {
                $query->where($this->tagsId, '<>', 1);
            });
    }
}
